/**
 * @description  券池审批
 * @author shenhong
 */
import React, { PropTypes, PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, message, Radio, Row, Col, Select, Spin, Upload } from 'antd';
import { SecondHeaderC, PrimaryC, PrimaryGhostC, ModalC, TableC, UploadC } from '../../../../comps';
import style from './index.less';
import ColRender from './colRender';
import ColRender2 from './colRender2';
import moment from 'moment';
import uuid from 'es6-uuid';
import { fill } from 'lodash';
import { isZiGuanEvir, exportFile } from '../../../../utils/commonFunc';
const { TextArea } = Input;

const FormItem = Form.Item;
const FormItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  },
};
@Form.create()
class myModal extends PureComponent {
  // props默认值
  static defaultProps = {
    onRef: () => {}, // 本组件的引用
  };

  constructor() {
    super();

    this.state = {
      value: 'manual',
      isShow: false, //是否展示组件内容
      defaultData: {},
      isError: false, // 校验标的要素是否有必填项未填
      isError2: false, // 校验条目要素是否有必填项未填
      isOver: false, // 判断失效日期是否大于生效日期/今天
      fileList: [], //文件上传
      isZiGuan: false,
      uploadShow: false, //自动方式模板上传模态框
      uploadData: {}, //模板上传数据
      teplataId: undefined,
      uploadShowLoading: false,
      uploadCref: undefined,
    };
  }
  componentDidMount() {
    this.props.onRef(this);
    const {
      globalM: { dataDictionary = {} },
      type,
      detailData,
      dispatch,
    } = this.props;
    const pageInfo = {
      currentPage: 1,
      numInPage: 20,
    };
    let temp = isZiGuanEvir();
    let isZiGuan = !!temp; // 判断该页面是在资管被引入的，还是maat
    this.setState({ isZiGuan });
    dispatch({
      type: 'ApprovalUtilsM/save', // 获取字典值
      payload: {
        selectData: dataDictionary,
      },
    });
    dispatch({
      type: 'ApprovalUtilsM/getPoolName', // 获取券池名称下拉
      payload: {},
    });
    dispatch({
      type: 'couponPoolDefinitionM/saerchName',
      payload: {
        name: '',
        pageInfo,
      },
    });
    dispatch({
      type: 'ApprovalUtilsM/getUserInfo',
      payload: localStorage.getItem('antd-pro-userId'), // 获取对当前用户信息
      callback: (res) => {
        this.setState({
          currentUser: res,
        });
      },
    });
    dispatch({
      type: 'ApprovalUtilsM/findTag', // 获取标签
      payload: {},
    });
    dispatch({
      type: 'ApprovalUtilsM/findResearcher', // 获取研究员
      payload: { roleCode: 'research_person' },
    });
    if (type == 'outPool2') {
      this.setState({
        value: 'manual',
        defaultData: detailData,
        isShow: true,
      });
    } else if (type == 'add') {
      this.setState({
        value: 'manual',
        isShow: true,
      });
    } else {
      dispatch({
        type: 'ApprovalUtilsM/getDetails', // 获取回填信息
        payload: { id: this.props.recordId },
        callback: (res) => {
          const data = res.dataSource;
          if (data.files) {
            //回填文件
            // this.changeFileList(data.files);
            this.setState({
              fileList: data.files,
            });
          }
          this.setState(
            {
              defaultData: data,
            },
            () => {
              this.setState({
                isShow: true,
              });
            },
          );

          if (type == 'edit') {
            this.setState({
              value: data.inPoolWay,
            });
          } else if (type == 'see') {
            this.setState({
              value: data.inPoolWay,
            });
          } else if (type == 'outPool') {
            this.setState({
              value: 'manual',
            });
          } else if (type == 'request') {
            this.setState({
              value: 'auto',
            });
          }
        },
      });
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    //type类型改变时重置表单
    if (nextProps.type !== this.props.type) {
      this.props.onRef(this);
      const { form } = this.props;
      form.resetFields();
    }
  }
  // 判断标的是否有重复
  isBeing = (arr) => {
    var hash = {};
    for (var i in arr) {
      if (hash[arr[i]]) {
        return true;
      }
      hash[arr[i]] = true;
    }
    return false;
  };

  // 清楚缓存
  resetDatas = () => {
    const { form } = this.props;
    form.resetFields();
    if (this.state.isShow) {
      this.childTwo2.handleReset();
    }
  };

  //点击单选按钮执行操作
  onChange = (e) => {
    this.setState({
      value: e.target.value,
    });
    this.props.form.setFieldsValue({ direction: undefined });
  };
  //券池名称下拉框输入事件
  couponPoolSearch = (e) => {
    const pageInfo = {
      currentPage: 1,
      numInPage: 20,
    };
    const { timeOutGap } = this.state;
    const { dispatch } = this.props;
    if (e) {
      this.timer ? clearTimeout(this.timer) : '';
      this.timer = setTimeout(() => {
        dispatch({
          type: 'couponPoolDefinitionM/saerchName',
          payload: {
            name: e,
            pageInfo,
          },
        });
      }, timeOutGap);
    }
  };

  // 券池名称改变时联想出券池类型的值
  handleChange = (value) => {
    const {
      form: { setFieldsValue },
      couponPoolDefinitionM: { nameData },
    } = this.props;
    if (value) {
      nameData.dataSource.map((item) => {
        if (value == item.id) {
          setFieldsValue({
            poolType: item.assetClass,
          });
        }
      });
      this.childTwo.changePoolName();
      this.childTwo2.changePoolName();
    }
  };
  // 渲染查询表单
  formRender = () => {
    const {
      form: { getFieldDecorator },
      dispatch,
      type,
      ApprovalUtilsM: { selectData, poolNameData, currentUser },
      couponPoolDefinitionM: { nameData },
    } = this.props;
    const selectType = selectData.SECURITYPOOL_ASSETCLASS;
    const selectDirecton =
      this.state.value == 'auto'
        ? [{ title: '入池', value: '1' }]
        : [
            { title: '出池', value: '2' },
            { title: '入池', value: '1' },
          ];
    const defaultData = this.state.defaultData;

    return (
      <div className={style.normalDom}>
        <Form>
          <Row>
            <Col span={8}>
              <FormItem {...FormItemLayout} label={'流程名称'}>
                {getFieldDecorator('flowName', {
                  initialValue: type !== 'add' && type !== 'outPool2' && type !== 'outPool' ? defaultData.flowName || '' : '',
                  rules: [{ required: true, message: `请输入流程名称` }],
                  getValueFromEvent: (event) => {
                    return event.target.value.replace(/\s+/g, '');
                  },
                })(<Input placeholder='请输入' style={{ width: '100%' }} disabled={type == 'see' ? true : false} />)}
              </FormItem>
            </Col>

            <Col span={8}>
              <FormItem {...FormItemLayout} label={'券池名称'}>
                {getFieldDecorator('securityId', {
                  initialValue: type !== 'add' ? defaultData.securityId || '' : '',
                  rules: [
                    { required: true, message: `请输入` },
                    { max: 50, message: '最大不可超过50个字符' },
                  ],
                })(
                  <Select
                    placeholder='请选择券池名称'
                    filterOption={false}
                    style={{ width: '100%' }}
                    showSearch={true}
                    onSearch={this.couponPoolSearch}
                    onChange={this.handleChange}
                    disabled={type == 'see' || type == 'outPool' || type == 'outPool2' || type == 'request' ? true : false}
                  >
                    {nameData.dataSource
                      ? nameData.dataSource.map((item) => {
                          return (
                            <Select.Option key={item.id} value={item.id}>
                              {item.name}
                            </Select.Option>
                          );
                        })
                      : null}
                  </Select>,
                )}
              </FormItem>
            </Col>

            <Col span={8}>
              <FormItem {...FormItemLayout} label={'券池类型'}>
                {getFieldDecorator('poolType', {
                  initialValue: type !== 'add' ? defaultData.securityType || '' : '',
                  rules: [{ required: true, message: `请选择` }],
                })(
                  <Select style={{ width: '100%' }} placeholder='请选择' disabled={true}>
                    {selectType
                      ? selectType.map((item) => {
                          return (
                            <Select.Option key={item.code} value={item.code}>
                              {item.value}
                            </Select.Option>
                          );
                        })
                      : null}
                  </Select>,
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem {...FormItemLayout} label={'操作方向'}>
                {getFieldDecorator('direction', {
                  initialValue: type !== 'add' ? (type == 'outPool' || type == 'outPool2' ? '2' : defaultData.direction || '') : '',
                  rules: [{ required: true, message: `请选择操作方向` }],
                })(
                  <Select style={{ width: '100%' }} placeholder='请选择' disabled={type == 'see' || type == 'outPool' || type == 'outPool2' || type == 'request' ? true : false}>
                    {selectDirecton
                      ? selectDirecton.map((item) => {
                          return (
                            <Select.Option key={item.value} value={item.value}>
                              {item.title}
                            </Select.Option>
                          );
                        })
                      : null}
                  </Select>,
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem {...FormItemLayout} label={'流程申请人'}>
                {getFieldDecorator('applicant', {
                  initialValue: type !== 'add' ? defaultData.applicant || '' : currentUser.name,
                })(<Input style={{ width: '100%' }} placeholder='请选择' disabled={true} />)}
              </FormItem>
            </Col>
            {this.state.value == 'manual' ? (
              <div className={style.remarkCol}>
                <Col span={24} className={style.approvalRemark}>
                  <FormItem label={'备注'}>
                    {getFieldDecorator('remark', {
                      initialValue: type !== 'add' ? defaultData.remark : undefined,
                    })(<TextArea style={{ width: '100%', height: '60px' }} placeholder='' disabled={type == 'see' ? true : false} />)}
                  </FormItem>
                </Col>
              </div>
            ) : null}
          </Row>
          {this.state.value == 'manual' ? (
            <Row>
              <Col className={'bondApprovalUpload'}>
                <span className={'accessory '}>附件</span>
                <div style={{ display: 'inline-flex' }}>
                  <UploadC
                    value={this.state.fileList || []}
                    showUploadList={true}
                    isDelete={type == 'see' ? false : true}
                    disabled={type == 'see' ? true : false}
                    type={1}
                    multiple={true}
                    onRef={(e) => this.setState({ uploadCref: e })}
                  />
                </div>
              </Col>
            </Row>
          ) : null}
        </Form>
      </div>
    );
  };

  // 获取下方表格数据
  getData = (e) => {
    if (!this.state.isShow) return;
    const data = this.childTwo.getData(); // 标的要素
    const newdatas = this.childTwo2.getData2(); // 条目要素
    const {
      form: { validateFields },
      rowId,
    } = this.props;
    let dataObj = undefined;
    let queryD = {};
    if (newdatas && newdatas.length) {
      newdatas.map((item) => {
        if (item.effectiveTime) {
          item.effectiveTime = item.effectiveTime.format('YYYY-MM-DD');
        }
        if (item.expirationTime) {
          item.expirationTime = item.expirationTime.format('YYYY-MM-DD');
        }
      });
    }
    validateFields((err, fieldsValue) => {
      queryD = fieldsValue;
      queryD.value = this.state.value;
    });
    const fileList = this.state.uploadCref?.getFileList();
    console.log(fileList, '---');
    if (fileList === null) return;
    if (fileList.length) {
      //文件上传部分

      queryD.files = fileList;
    }
    if (this.props.type == 'see') {
      dataObj = 'see';
    } else {
      const query = queryD; // 上方表单
      const datas = data; // 标的要素
      const newdatas2 = newdatas; // 条目要素
      const arr = {
        direction: query.direction,
        securityId: query.securityId,
        flowName: query.flowName,
        item: datas,
        inPoolWay: query.value,
        files: query.files, //手动
        remark: query.remark,
      };
      const arr2 = {
        direction: query.direction,
        securityId: query.securityId,
        flowName: query.flowName,
        item: newdatas2,
        inPoolWay: query.value,
        //  file:query.file,
        //  remark:query.remark,
      };
      if (query.value == 'manual') {
        // 手动入池方式执行
        let flag = false;
        const biaoDe = [];
        if (datas && datas.length) {
          datas.map((item) => {
            biaoDe.push(item.tradingCode + '-' + item.exchangeCode);
            if (item.tradingCode !== undefined && item.exchangeCode !== '' && item.exchangeCode !== undefined && item.exchangeCode !== '') {
              flag = true;
            } else {
              flag = false;
            }
          });
        }
        const isBeing = this.isBeing(biaoDe);
        if (flag) {
          if (query.title2 && query.title2.length) {
            arr.tagId = query.title2;
          }
          if (isBeing) {
            message.warning('标的信息重复，请重新选择');
          } else {
            if (
              arr.flowName !== undefined &&
              arr.flowName !== '' &&
              arr.securityId !== undefined &&
              arr.securityId !== '' &&
              arr.inPoolWay !== undefined &&
              arr.inPoolWay !== '' &&
              arr.direction !== undefined &&
              arr.direction !== ''
            ) {
              dataObj = arr;
              this.setState({ isError: false });
            } else {
              this.setState({ isError: false });
            }
          }
        } else {
          this.setState({ isError: true });
        }
      } else if (queryD.value == 'auto') {
        if (newdatas2 && newdatas2.length) {
          let flag = false;
          let overs = false;
          const newArr = [];
          newdatas2.map((item) => {
            newArr.push(item.dimension + item.symbol + item.content);
            if (
              item.content == undefined ||
              item.content == '' ||
              item.expirationTime == undefined ||
              item.expirationTime == '' ||
              item.effectiveTime == undefined ||
              item.effectiveTime == ''
            ) {
              // 校验条目要素必填项
              flag = true;
            }
            const stTime = new Date(item.expirationTime); // 失效时间
            const edTime = new Date(item.effectiveTime); // 生效时间
            const todTime = new Date(moment().format('YYYY-MM-DD')); // 当前时间
            if (stTime < edTime || stTime < todTime) {
              overs = true;
            }
            this.setState({
              isOver: overs,
            });
          });
          const isBeing2 = this.isBeing(newArr);
          if (flag) {
            this.setState({
              isError2: true,
            });
          } else if (overs) {
            this.setState({
              isOver: true,
              isError2: false,
            });
          } else {
            if (
              arr2.flowName !== undefined &&
              arr2.flowName !== '' &&
              arr2.securityId !== undefined &&
              arr2.securityId !== '' &&
              arr2.inPoolWay !== undefined &&
              arr2.inPoolWay !== '' &&
              arr2.direction !== undefined &&
              arr2.direction !== ''
            ) {
              if (isBeing2) {
                message.warning('条目要素重复，请重新选择');
              } else {
                dataObj = arr2;
                this.setState({
                  isError2: false,
                  isOver: false,
                });
              }
            } else {
              this.setState({
                isError2: false,
              });
            }
          }
        } else {
          this.setState({
            isError2: true,
          });
        }
      }
    }
    return dataObj;
  };
  // 手动模板下载
  download = () => {
    const {
      user: { currentUser = {} },
    } = this.props;
    const ivUser = currentUser.userId;
    exportFile('gateway/portfolio-server/flowSecurity/download-template', { ivUser: ivUser });
  };
  errorColumnsChange = (columns) => {
    let newColumns = [];
    if (columns) {
      columns.map((item) => {
        if (item.key != 'errormessage') {
          item.align = 'center';
        }
      });
    }
    return columns;
  };
  //模板上传模态框
  templateUpLoad = () => {
    const { uploadShow, uploadData } = this.state;
    let errorColumns = this.errorColumnsChange(uploadData?.errorColumns);
    const modalProps = {
      destroyOnClose: true,
      visible: uploadShow,
      maskClosable: true,
      title: '提示',
      width: 700,
      onCancel: () => {
        this.setState({
          uploadShow: false,
        });
      },
      onOk: () => {
        this.setState({
          uploadShow: false,
          uploadData: uploadData.dataSource,
          teplataId: uuid(32),
        });
      },
    };

    return (
      <ModalC {...modalProps}>
        <div className={style.batchUploadOne}>
          共{uploadData?.total}条，其中，导入成功，{uploadData?.success}条；导入失败，{uploadData?.error}条。
        </div>
        <div className={style.batchUpload}>点击取消，重新导入；点击确定，导入成功的标的会自动填充到新建标的列表。</div>
        {uploadData?.error != '0' && (
          <TableC
            columns={errorColumns}
            // loading={this.props.loading.effects["gateway/portfolio-server/flowSecurity/importFlow"]}
            // scroll={{ y: '231px' }}
            dataSource={uploadData?.errorDataSource}
            rowKey='id'
            hidePage={true}
          />
        )}
      </ModalC>
    );
  };
  //新增
  addRow = () => {
    this.childTwo.addRow();
  };
  render() {
    const {
      form,
      type,
      ApprovalUtilsM: { selectData, tagData, researchers },
      toolText,
      loading,
    } = this.props;
    const { isShow, isError, isError2, isOver, teplataId, isZiGuan, uploadData, template, uploadShowLoading } = this.state;
    const defaultData = this.state.defaultData;
    const flag = type == 'see' || type == 'outPool' || type == 'outPool2' || type == 'request' ? true : false; // 不同类型的入池方式是否置灰
    // const poolType = (type !== 'add' || type != 'edit') ? defaultData && defaultData.securityType ? defaultData.securityType : form.getFieldValue('poolType') : form.getFieldValue('poolType');
    const poolType = form.getFieldValue('poolType');
    const isdisplay = this.state.value == 'manual' ? 'block' : 'none';
    const isdisplay2 = this.state.value == 'auto' ? 'block' : 'none';
    const title = this.state.value == 'manual' ? '标的要素' : '条目要素';

    return (
      <div className={style.modals}>
        <Spin spinning={type == 'add' || type == 'outPool2' ? false : loading.effects['ApprovalUtilsM/getDetails'] == true}>
          {isShow ? (
            <div>
              {' '}
              <div style={{ marginLeft: '20px' }}>
                <span>入池方式&nbsp;:&nbsp;&nbsp;</span>
                <Radio.Group onChange={this.onChange} value={this.state.value} disabled={flag}>
                  <Radio value={'manual'}>手动</Radio>
                  {!isZiGuan && <Radio value={'auto'}>自动</Radio>}
                </Radio.Group>
              </div>
              {defaultData && defaultData.flowState == '2' ? (
                <div className='applicant'>
                  <span>{`下一审批人：${defaultData.approve}`}</span>
                </div>
              ) : null}
              <div style={{ marginTop: '20px' }}>
                <SecondHeaderC title='通用要素' />
                {this.formRender()}
              </div>
              <div style={{ marginTop: '15px' }}>
                <SecondHeaderC title={`${title}`} />
                {this.state.value == 'manual' && (
                  <div style={{ marginBottom: '35px' }}>
                    <div style={{ float: 'left', marginLeft: '10px', marginBottom: '10px' }}>
                      <PrimaryC title='新增' disabled={poolType ? (type == 'see' || type == 'outPool2' ? true : false) : true} onClick={this.addRow} />
                    </div>
                    <div style={{ float: 'right' }}>
                      <PrimaryGhostC title='模板下载' onClick={this.download} style={{ marginRight: '10px' }} />

                      <UploadC
                        value={this.state.fileList || []}
                        showUploadList={false}
                        type={1}
                        data={{ type: poolType }}
                        action='gateway/file/portfolio-server/flowSecurity/importFlow'
                        disabled={poolType && type != 'see' ? false : true}
                        accept='.xlsx,.xls'
                        onUpload={(e) => {
                          if (e.code == 0) {
                            this.setState({
                              uploadData: e.importVo,
                              uploadShow: true,
                              uploadShowLoading: false,
                            });
                          } else {
                            this.setState({
                              uploadShowLoading: false,
                            });
                            message.error(e.msg);
                          }
                        }}
                        style={{ display: 'inline' }}
                        // onRef={e => this.setState({ uploadCref: e })}
                      />
                      {/* <Upload {...uploadProps} disabled={uploadShowLoading}>
                    <Spin spinning={uploadShowLoading}>
                      <PrimaryGhostC title='模板上传' disabled={(poolType && type != 'see') ? false : true} />
                    </Spin>
                  </Upload> */}
                    </div>
                  </div>
                )}
                {this.templateUpLoad()}
                <div className='isOver'>
                  <div style={{ display: `${isdisplay}` }}>
                    <ColRender
                      onRef={(ref) => (this.childTwo = ref)}
                      poolType={poolType}
                      isError={isError}
                      teplataId={teplataId}
                      uploadData={uploadData ? uploadData : []}
                      isDisabled={type == 'see' ? true : false}
                      tagData={tagData}
                      researchers={researchers}
                      randomText={this.props.randomText}
                      type={type}
                      values={this.state.value}
                      defaultData={defaultData && defaultData.item ? defaultData.item : []}
                      defaultDataAll={defaultData ? defaultData : []}
                      toolText={toolText}
                      direction={form.getFieldValue('direction')}
                      securityId={form.getFieldValue('securityId')}
                    />
                  </div>
                  <div style={{ display: `${isdisplay2}` }}>
                    <ColRender2
                      poolType={poolType}
                      isError={isError}
                      isOver={isOver}
                      isDisabled={type == 'see' ? true : false}
                      isError2={isError2}
                      onRef={(ref) => (this.childTwo2 = ref)}
                      selectData={selectData}
                      tagData={tagData}
                      randomText={this.props.randomText}
                      type={type}
                      defaultData={defaultData.itemAuto}
                    />
                  </div>
                </div>
              </div>
            </div>
          ) : (
            <div></div>
          )}
        </Spin>
      </div>
    );
  }
}

export default connect(({ couponPoolApprovalM, ApprovalUtilsM, loading, userM: user, bondAnalysisM, couponPoolDefinitionM, globalM }) => ({
  couponPoolApprovalM,
  ApprovalUtilsM,
  loading,
  user,
  couponPoolDefinitionM,
  bondAnalysisM,
  globalM,
}))(myModal);
